import {defineStore} from "pinia";
import {reactive, type UnwrapNestedRefs} from "vue";
import type {Visitor} from "@/models/visitor";
import {getVisitor} from "@/apis/api";

const visitorStore =defineStore('visitor',  () => {
    let v:any = localStorage.getItem('visitor');
    if(v) {
        v = JSON.parse(v);
    }else{
        v = {};
    }
    getVisitor(v.visitorId ?? '').then((res) => {
        let v = {
            visitorId: res['visitor_id'],
            usedTokens: res['use_token'],
        };
        localStorage.setItem('visitor', JSON.stringify(v))
        setVisitor(v);
    });
    const visitor:UnwrapNestedRefs<Visitor> = reactive<Visitor>(v);
    const setVisitor = (v: Visitor) => {
        visitor.visitorId = v.visitorId;
        if(v.freeTimes !== undefined) {
            visitor.freeTimes = v.freeTimes;
        }
        if (v.usedTokens !== undefined) {
            visitor.usedTokens = v.usedTokens;
        }

        if (v.visitTime !== undefined) {
            visitor.visitTime = v.visitTime;
        }
    }

    const getVisitorId = () => {
        return visitor.visitorId;
    }
    return {visitor, setVisitor, getVisitorId};
})

export default visitorStore;